package com.cxb.carrecorder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.xutils.x;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.os.StatFs;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cxb.carrecorder.VideoRecorder.RecorderListener;

public class PreviewService extends Service implements SurfaceHolder.Callback,
		Callback, OnImageUploadCallBack {
	private SurfaceView surfaceView = null;
	public static VideoRecorder recorder = null;
	private SurfaceHolder surfaceHolder;
	private int nAvailableMin = 500;
	private int recordTimeLevel = 2;
	private int resolutionLevel = 1;
	private boolean bMute = true;
	private String szPath = null;
	private int menuBarHideTimeCount = 0;
	private View view = null;
	private WindowManager mWindowManager = null;
	private WindowManager.LayoutParams wmParams = null;
	private final int SW_HIDE = 0;
	private final int SW_SHOW = 1;
	private final int SW_NAVI = 2;
	private final int SW_SHOW_SHARE_VIDEO = 3;
	private final int SW_HIDE_SHARE_VIDEO = 4;
	private final int SW_SHOW_SHARE_PICTURE = 5;
	private final int SW_HIDE_SHARE_PICTURE = 6;
	private int nPreviewMode = -1;
	private TextView timeText = null;
	private TextView worningText = null;

	// private ImageView muteIcon = null;
	private ImageView lockedIcon = null;
	private ImageView recordIcon = null;
	private ImageButton recordButton = null;
	private LinearLayout taskbarLayout = null;

	private LinearLayout shareTimeLayout = null;
	private LinearLayout shareButtonLayout = null;
	private Handler mHandler;

	private static final int MSG_HIDE_MENU_BAR = 0x001;
	private View coverView, worning;;
	private static boolean firstBoot = true;
	// private static boolean isTestMode = false;
	private AlertDialog lockedFile2More;
	public static boolean isFullScreenShow = false;
	public static boolean isPowerOffing = false;
	private DimissDialogTask dialogTask;

	private final static String ACTION_START_UPLOAD_IMAGE = "ACTION_START_UPLOAD_IMAGE";
	private final static String ACTION_CANCEL_UPLOAD_IMAGE = "ACTION_CANCEL_UPLOAD_IMAGE";

	private final static String ACTION_GET_PICTURE_SHARE = "ACTION_GET_PICTURE_SHARE";
	private final static String ACTION_GET_VIDEO_SHARE = "ACTION_GET_VIDEO_SHARE";
	public final static String ACTION_START_FORMAT_SDCARD = "ACTION_START_FORMAT_SDCARD";
	private EventCallBack mShareCallBack = null;
	private TextView mShareTimeView = null;
	private ImageView mSharePictureView = null;
	private ImageView mRecordView = null;
	private String mShareFile = null;
	private boolean mIsSharing = false;
	private SoundPool pool;
	private int sourceid = -1;

	private final DeleteFileService mBinder = new DeleteFileService();
	private PersistUtils persistUtils;



	@Override
	public void onCreate() {
		super.onCreate();
		showCarRecorderStart();
		// startForeground(0,null);
		persistUtils = new PersistUtils(this);
		mHandler = new Handler(this);
		dialogTask = new DimissDialogTask();
		if (CarRecorderDebug.DEBUG)
			szPath = Environment.getExternalStorageDirectory() + "/log.txt";
		CarRecorderDebug.printf("PreviewWindowService.onCreate", szPath);
		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(getApplicationContext());
		checkExternalSDcardSize();
		createWindowView();
		initSound();
		SharedPreferences sharedPreferences = getSharedPreferences("Config",
				Context.MODE_PRIVATE);
		recordTimeLevel = sharedPreferences.getInt("RecordTime", 2);
		resolutionLevel = sharedPreferences.getInt("Resolution", 1);
		bMute = sharedPreferences.getBoolean("Mute", bMute);

		IntentFilter mFilterSD = new IntentFilter();
		mFilterSD.addAction(Intent.ACTION_MEDIA_MOUNTED);
		mFilterSD.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		mFilterSD.addAction(Intent.ACTION_MEDIA_EJECT);
		mFilterSD.addDataScheme("file");
		registerReceiver(mReceiverSD, mFilterSD);

		IntentFilter mFilterShutDown = new IntentFilter();
		mFilterShutDown.addAction(Intent.ACTION_SHUTDOWN);
		registerReceiver(mReceiverShutDown, mFilterShutDown);

		IntentFilter mFilterTestMode = new IntentFilter();
		mFilterTestMode.addAction("action.cxb.testmode");
		registerReceiver(mStartTestMode, mFilterTestMode);

		IntentFilter mFilterRecord = new IntentFilter();
		mFilterRecord.addAction("lock_record_file");

		mFilterRecord.addAction("preview_window_off");
		mFilterRecord.addAction("preview_window_on");
		mFilterRecord.addAction("sound_on");
		mFilterRecord.addAction("sound_off");
		mFilterRecord.addAction("action_upload_image");
		mFilterRecord.addAction("action_poweroff_dialog_show");
		mFilterRecord.addAction("action_poweroff_dialog_cancel");
		mFilterRecord.addAction("action.power_offing");

		// add by xrx
		mFilterRecord.addAction("action_get_camera_picture");
		mFilterRecord.addAction("action_get_camera_video");
		mFilterRecord.addAction("action_get_camera_data");
		mFilterRecord.addAction(ACTION_START_FORMAT_SDCARD);

		registerReceiver(mReceiverRecord, mFilterRecord);

		updateTime.post(updateTimeThread);
		surfaceView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!mIsSharing)
					taskbarLayout.setVisibility(View.VISIBLE);
				menuBarHideTimeCount = 0;
			}
		});
		new Thread(new MenuBarHideTask()).start();

		// mHandler.postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// recorder.start(false);
		// recorder.uploadPre10sImage(getApplicationContext());
		//
		// }
		// }, 10000);

		lockedFile2More = new AlertDialog.Builder(this)
				.setTitle(R.string.verify)
				.setMessage(R.string.lock_file_too_more)
				.setPositiveButton(R.string.cancel,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();

							}
						})
				.setNegativeButton(R.string.clear_lock_files,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								dialog.cancel();
								File lockDir = new File(
										VideoRecorder.VIDEOS_PATH_LOCKED);
								File[] lockedFiles = lockDir.listFiles();
								if (lockedFiles != null) {
									for (File f : lockedFiles) {
										f.delete();
									}
								}
								playTts(getString(R.string.clear_success));
							}
						}).create();

		lockedFile2More.getWindow().setType(
				WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

		mShareCallBack = new EventCallBack();
		mShareCallBack.setCallBack(new IShareCallBack() {
			@Override
			public void onVideoComplete(String strFile) {
				// TODO Auto-generated method stub
				mShareFile = strFile;
				Message msg = new Message();
				msg.what = 1;
				handlerShare.sendMessage(msg);
			}

			@Override
			public void onPictureShareComplete(final String strFile) {
				// TODO Auto-generated method stub
				x.task().post(new Runnable() {

					@Override
					public void run() {
						if (pool != null && sourceid != -1)
							pool.play(sourceid, 1, 1, 0, 0, 1);
						FileInputStream fs = null;
						try {
							fs = new FileInputStream(strFile);
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}

						if (fs != null) {
							Bitmap bitmap = BitmapFactory.decodeStream(fs);
							mSharePictureView.setImageBitmap(bitmap);
							mSharePictureView.setVisibility(View.VISIBLE);
						}

						mShareFile = strFile;
						Message msg = new Message();
						msg.what = 2;
						handlerShare.sendMessage(msg);

					}
				});

			}
		});

	}

	private void initSound() {
		pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
		sourceid = pool.load(this, R.raw.pshutter, 0);
	}

	private boolean isSDCardExist() {
		File filesd = new File("/storage/sdcard1");
		CarRecorderDebug.printfPhotoLog("filesd.exists() " + filesd.exists()
				+ " filesd.canWrite() " + filesd.canWrite());
		return filesd.exists() && filesd.canWrite();
	}

	private int state_window = 0;

	private int checkState_window() {
		return state_window;
	}

	private boolean alreadyUpload = false;

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("test", "recorder onStartCommand");
		if (intent == null) {
			return 1;
		} else if (ACTION_START_UPLOAD_IMAGE.equals(intent.getAction())) {
			CarRecorderDebug.printfPhotoLog("ACTION_START_UPLOAD_IMAGE");
			isPowerOffing = true;
			try {
				if (recorder == null) {

					recorder = VideoRecorder.getInstance(
							surfaceView.getHolder(), this);

				}
				preState = recorder.isRecording();
				recorder.start(false);
				if (preState) {
					CarRecorderDebug.printfRECORDERLog("image　开始传图２");
					recorder.uploadPre10sImage(PreviewService.this, null);
				} else {
					CarRecorderDebug.printfRECORDERLog("image　开始传图");
					recorder.uploadImage(PreviewService.this);
				}
				alreadyUpload = true;
			} catch (Exception e) {

				e.printStackTrace();
			}

		} else if (ACTION_CANCEL_UPLOAD_IMAGE.equals(intent.getAction())) {
			try {
				isPowerOffing = false;
				if (alreadyUpload) {
					if (preState && recorder != null) {
						recorder.start(true);
					}

				}
				alreadyUpload = false;
				// recorder.uploadImage(PreviewService.this);
			} catch (Exception e) {

				e.printStackTrace();
			}
		} else if (ACTION_GET_PICTURE_SHARE.equals(intent.getAction())) {
			if (checkState_window() > 0) {
				return super.onStartCommand(intent, flags, startId);
			}
			state_window = 2;
			try {
				if (mIsSharing)
					return 1;
				mIsSharing = true;
				updateViewPosition(SW_SHOW_SHARE_PICTURE);
				recorder.startShotPicture(mShareCallBack);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (ACTION_GET_VIDEO_SHARE.equals(intent.getAction())) {
			if (checkState_window() > 0) {
				return super.onStartCommand(intent, flags, startId);
			}
			state_window = 3;
			try {
				if (mIsSharing)
					return 1;
				mIsSharing = true;
				updateViewPosition(SW_SHOW_SHARE_VIDEO);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			if (checkState_window() > 0) {
				return super.onStartCommand(intent, flags, startId);
			}
			if (intent != null && intent.getBooleanExtra("setup_ui", false)) {
				updateViewPosition(SW_SHOW);

			} else if (intent != null
					&& intent.getBooleanExtra("uploadImage", false)) {
				// uploadImage

				try {
					if (recorder == null) {

						recorder = VideoRecorder.getInstance(
								surfaceView.getHolder(), this);
					}
					recorder.uploadImage(PreviewService.this);

				} catch (Exception e) {

					e.printStackTrace();
				}

			}
		}
		// ////////////////////////////////////////////////////////////////////
		// new Handler().postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// try {
		// recorder.uploadImage(PreviewService.this);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }
		// }, 6000);
		//
		// /////////////////////////////////////////////////////////////////
		return super.onStartCommand(intent, flags, startId);
	}

	private void setRecording(boolean isRecording) {
		if (isRecording) {
			recordIcon.setVisibility(View.VISIBLE);
			AnimationDrawable animationDrawable = (AnimationDrawable) recordIcon
					.getDrawable();
			animationDrawable.start();
		} else {
			recordIcon.setVisibility(View.GONE);
		}
	}

	private void closeActivity() {
		updateViewPosition(SW_HIDE);

		/**
		 * 閿熸枻鎷烽敓鏂ゆ嫹閿熷壙绛规嫹閿熷鎾�
		 */

		Intent intent = new Intent(MainActivity.ACTION_FINISH_SELF);
		sendBroadcast(intent);
		mIsSharing = false;
	}

	private void createWindowView() {

		view = LayoutInflater.from(this).inflate(R.layout.preview_window, null);

		view.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				Log.d("pumkid", "KeyEvent.KEYCODE_BACK" + keyCode);
				if (KeyEvent.KEYCODE_F1 == keyCode) {
					closeActivity();
				}
				/** 閿熸枻鎷烽敓鎴》鎷锋椂閿熸埅闂枻鎷烽敓鏂ゆ嫹 **/
				if (KeyEvent.KEYCODE_BACK == keyCode) {

					closeActivity();
				}
				return false;
			}
		});
		coverView = view.findViewById(R.id.coverView);

		mWindowManager = (WindowManager) getApplicationContext()
				.getSystemService(Context.WINDOW_SERVICE);
		wmParams = new WindowManager.LayoutParams();

		wmParams.type = 2002;
		wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
				| LayoutParams.FLAG_NOT_FOCUSABLE;
		wmParams.screenOrientation = 0;
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;
		wmParams.width = 1;
		wmParams.height = 1;
		coverView.setVisibility(View.VISIBLE);

		surfaceView = (SurfaceView) view.findViewById(R.id.surfaceView);
		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		surfaceHolder.addCallback(this);
		mWindowManager.addView(view, wmParams);

		mShareTimeView = (TextView) view.findViewById(R.id.share_time);
		mSharePictureView = (ImageView) view.findViewById(R.id.share_picture);
		mRecordView = (ImageView) view.findViewById(R.id.record);

		timeText = (TextView) view.findViewById(R.id.time);
		worningText = (TextView) view.findViewById(R.id.worningtext);
		worning = view.findViewById(R.id.worning);
		// muteIcon = (ImageView) view.findViewById(R.id.mute);
		lockedIcon = (ImageView) view.findViewById(R.id.locked);
		recordIcon = (ImageView) view.findViewById(R.id.record);
		taskbarLayout = (LinearLayout) view.findViewById(R.id.taskbar);

		shareTimeLayout = (LinearLayout) view
				.findViewById(R.id.share_time_layout);
		shareButtonLayout = (LinearLayout) view.findViewById(R.id.share_bar);

		recordButton = (ImageButton) view.findViewById(R.id.start_button);
		recordButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (recorder == null) {
					CarRecorderDebug.printf("recorder==null", szPath);
				} else {
					if (recorder.isRecording()) {
						recorder.start(false);

					} else {
						long available = checkSDcard();
						if (available >= nAvailableMin) {
							recorder.start(true);
							showWarning(false, null);
						} else if (available < 0) {
							showWarning(true, getString(R.string.cardverify));
						} else
							showWarning(true, getString(R.string.lowstorage));
					}
				}
			}
		});

		ImageButton listButton = (ImageButton) view
				.findViewById(R.id.list_button);
		listButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (checkSDcard() >= 0) {

					try {
						Intent intent = new Intent();
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setClass(getApplicationContext(),
								FolderActivity.class);
						startActivity(intent);
						mHandler.postDelayed(new Runnable() {

							@Override
							public void run() {
								updateViewPosition(SW_HIDE);
							}
						}, 300);

					} catch (Exception e) {
						CarRecorderDebug.printf(e.toString(), szPath);
					}
				} else
					showWarning(true, getString(R.string.cardverify));
			}
		});

		ImageButton settingbutton = (ImageButton) view
				.findViewById(R.id.setting_button);
		settingbutton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					Intent intent = new Intent();
					// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setClass(getApplicationContext(),
							SettingActivity.class);
					startActivity(intent);
					mHandler.postDelayed(new Runnable() {

						@Override
						public void run() {
							updateViewPosition(SW_HIDE);
						}
					}, 300);
				} catch (Exception e) {
					CarRecorderDebug.printf(e.toString(), szPath);
				}
			}
		});

		ImageButton homeButton = (ImageButton) view
				.findViewById(R.id.return_button);
		homeButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				closeActivity();
				// updateViewPosition(SW_SHOW_SHARE_VIDEO);
			}
		});

		ImageView cancelButton = (ImageView) view
				.findViewById(R.id.cancel_button);
		cancelButton.setOnClickListener(new ImageView.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (recorder != null)
					recorder.cancelShareVideo();
				updateViewPosition(SW_HIDE_SHARE_VIDEO);
				closeActivity();
			}
		});

	}

	boolean lastStateRecording = true;
	private BroadcastReceiver mReceiverSD = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) {

				checkExternalSDcardSize();

				if (!recorder.isRecording() && recorder != null
						&& checkSDcard() >= nAvailableMin) {
					// if (lastStateRecording) {
					recorder.start(true);
					// }
				}
				// firstBoot = false;

			}
			if ((intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED) || intent
					.getAction().equals(Intent.ACTION_MEDIA_EJECT))) {
				lastStateRecording = recorder.isRecording();
				if (recorder != null) {
					if (recorder.isRecording()) {
						recorder.start(false);
					}
				}
				showWarning(true, getString(R.string.cardverify));
			}
		}
	};

	private BroadcastReceiver mReceiverShutDown = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
				// if (recorder != null)
				// recorder.start(false);
			}
		}
	};
	private BroadcastReceiver mStartTestMode = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			if (recorder != null) {
				try {
					recorder.releaseCamera();
					stopSelf();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};

	boolean preState = true;
	private BroadcastReceiver mReceiverRecord = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("lock_record_file")) {
				boolean isQuickSave = intent.getBooleanExtra("isQuickSave",
						false);
				if (recorder != null && recorder.isRecording()) {

					if (isQuickSave) {
						// recorder.start(false);
						// recorder.start(true);
						// playTts(getString(R.string.lock_success_with_quick_save));
						if (!recorder.isLocked()) {
							playTts(getString(R.string.lock_success));
						}
						recorder.LockFile();
					} else {
						playTts(getString(R.string.lock_success));
						recorder.LockFile();
					}

					// ////////////褰曢敓鏂ゆ嫹閿熶茎纭锋嫹閿熸枻鎷烽敓鏂ゆ嫹鍟殿剨鎷烽敓鏂ゆ嫹鏉堫垽鎷烽敓锟�////////////////
					File lockDir = new File(VideoRecorder.VIDEOS_PATH_LOCKED);
					if (lockDir.exists()) {
						File[] lockedFiles = lockDir.listFiles();
						Log.i("record", "======lockedFiles.length="
								+ lockedFiles.length);
						if (lockedFiles != null && lockedFiles.length >= 5) {
							Utils.playTts(context,
									getString(R.string.lock_file_too_more),
									false);
							try {

								lockedFile2More.show();
								mHandler.removeCallbacks(dialogTask);
								mHandler.postDelayed(dialogTask, 15000);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
			} else if (action.equals("preview_window_off")) {
				updateViewPosition(SW_HIDE);
				closeActivity();
			} else if (action.equals("preview_window_on")) {
				updateViewPosition(SW_SHOW);
			} else if (action.equals("action_poweroff_dialog_show")) {
				try {
					Log.i("image", "关机框弹出");
					isPowerOffing = true;
					if (recorder != null) {

						preState = recorder.isRecording();
						Log.i("image", "开始传图");
						recorder.start(false);
						recorder.uploadImage(PreviewService.this);

					}

				} catch (Exception e) {

					e.printStackTrace();
				}
			} else if (action.equals("action_poweroff_dialog_cancel")) {
				try {
					isPowerOffing = false;
					if (preState && recorder != null) {
						recorder.start(true);
					}

					// recorder.uploadImage(PreviewService.this);
				} catch (Exception e) {

					e.printStackTrace();
				}
			} else if (ACTION_START_FORMAT_SDCARD.equals(action)) {
				if (recorder != null && recorder.isRecording()) {
					recorder.start(false);
				}
			}

			// if (action.equals("action.power_offing")) {
			// isPowerOffing = true;
			// mHandler.postDelayed(new Runnable() {
			//
			// public void run() {
			// shutDown();
			// };
			// }, 35000);
			// }
		}
	};

	private class MenuBarHideTask implements Runnable {

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(1000);
					menuBarHideTimeCount++;
					if (menuBarHideTimeCount >= 6) {
						mHandler.sendEmptyMessage(MSG_HIDE_MENU_BAR);
					}
				} catch (InterruptedException e) {

					e.printStackTrace();
				}
			}
		}

	}

	private void sendShareBroadcast(String strAction, String strFile) {
		Intent intent = new Intent();
		intent.putExtra("share_file", strFile);
		intent.setAction(strAction);
		sendBroadcast(intent);
	}

	private int currentFlag;

	private void updateViewPosition(int flag) {
		currentFlag = flag;
		switch (flag) {
		case SW_HIDE:
			view.setKeepScreenOn(false);

			wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
					| LayoutParams.FLAG_NOT_FOCUSABLE;
			if (recorder != null && recorder.isLocked()) {
				wmParams.width = 1;
				wmParams.height = 1;
				wmParams.gravity = Gravity.RIGHT | Gravity.TOP;
				lockedIcon.setBackgroundColor(Color.BLACK);
				lockedIcon.setVisibility(View.GONE);
			} else {
				wmParams.width = 1;
				wmParams.height = 1;
				wmParams.gravity = Gravity.RIGHT | Gravity.TOP;
				lockedIcon.setVisibility(View.GONE);
				coverView.setVisibility(View.VISIBLE);
			}
			timeText.setVisibility(View.VISIBLE);
			taskbarLayout.setVisibility(View.VISIBLE);
			mWindowManager.updateViewLayout(view, wmParams);
			isFullScreenShow = false;
			state_window = 0;
			break;

		case SW_SHOW:
			view.setKeepScreenOn(true);

			wmParams.width = LayoutParams.MATCH_PARENT;
			wmParams.height = LayoutParams.MATCH_PARENT;
			wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
					| LayoutParams.FLAG_NOT_FOCUSABLE;

			taskbarLayout.setVisibility(View.VISIBLE);
			coverView.setVisibility(View.GONE);
			if (recorder != null && recorder.isLocked()) {
				lockedIcon.setBackgroundColor(Color.TRANSPARENT);
				lockedIcon.setVisibility(View.VISIBLE);
			} else
				lockedIcon.setVisibility(View.GONE);
			timeText.setVisibility(View.VISIBLE);
			taskbarLayout.setVisibility(View.VISIBLE);
			mWindowManager.updateViewLayout(view, wmParams);
			isFullScreenShow = true;
			break;

		case SW_NAVI:
			view.setKeepScreenOn(true);
			wmParams.width = LayoutParams.MATCH_PARENT;
			wmParams.height = LayoutParams.MATCH_PARENT;
			taskbarLayout.setVisibility(View.GONE);
			coverView.setVisibility(View.GONE);
			if (recorder != null && recorder.isLocked()) {
				lockedIcon.setBackgroundColor(Color.TRANSPARENT);
				lockedIcon.setVisibility(View.VISIBLE);
			} else
				lockedIcon.setVisibility(View.GONE);
			timeText.setVisibility(View.GONE);
			taskbarLayout.setVisibility(View.GONE);
			mWindowManager.updateViewLayout(view, wmParams);
			break;
		case SW_SHOW_SHARE_VIDEO:
			view.setKeepScreenOn(true);
			coverView.setVisibility(View.GONE);
			lockedIcon.setVisibility(View.GONE);
			timeText.setVisibility(View.GONE);
			taskbarLayout.setVisibility(View.GONE);
			shareTimeLayout.setVisibility(View.VISIBLE);
			shareButtonLayout.setVisibility(View.VISIBLE);

			wmParams.width = (int) this.getResources().getDimension(
					R.dimen.share_window_width);
			wmParams.height = (int) this.getResources().getDimension(
					R.dimen.share_window_height);
			// wmParams.x = (int)
			// this.getResources().getDimension(R.dimen.share_window_x);
			// wmParams.y = (int)
			// this.getResources().getDimension(R.dimen.share_window_y);
			wmParams.gravity = Gravity.CENTER;
			wmParams.flags = LayoutParams.FLAG_ALT_FOCUSABLE_IM;
			mWindowManager.updateViewLayout(view, wmParams);
			// 在第4秒发送一个检查信号，如果encode在4秒前已结束，则可能由异常引起。如果4前时没结束，但是录制时间没有变化，也可能是encode出现问题
			handlerShare.postDelayed(new Runnable() {

				@Override
				public void run() {
					Message msg = new Message();
					msg.what = 201601181;
					handlerShare.sendMessage(msg);
				}
			}, 4000);
			if (recorder != null) {
				// recorder.stopPreView();
				// recorder.startPreView();
				// recorder.setPreViewCallback(recorder);
			}
			isFullScreenShow = true;
			showWarning(false);
			if (recorder != null)
				recorder.startEncodeVideo(mShareCallBack);
			new Thread(new ThreadShareTime()).start();
			break;
		case SW_HIDE_SHARE_VIDEO:
			// if(recorder != null)
			// recorder.setPreViewCallback(null);

			view.setKeepScreenOn(false);
			wmParams.width = 1;
			wmParams.height = 1;
			wmParams.x = 0;
			wmParams.y = 0;
			wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
					| LayoutParams.FLAG_NOT_FOCUSABLE;
			if (recorder != null && recorder.isLocked()) {
				lockedIcon.setBackgroundColor(Color.BLACK);
				lockedIcon.setVisibility(View.GONE);
			} else {
				lockedIcon.setVisibility(View.GONE);
				coverView.setVisibility(View.VISIBLE);
			}
			timeText.setVisibility(View.VISIBLE);
			taskbarLayout.setVisibility(View.VISIBLE);
			shareTimeLayout.setVisibility(View.GONE);
			shareButtonLayout.setVisibility(View.GONE);
			mWindowManager.updateViewLayout(view, wmParams);
			showWarning(true);
			isFullScreenShow = false;
			state_window = 0;
			break;
		case SW_SHOW_SHARE_PICTURE:

			view.setKeepScreenOn(true);
			taskbarLayout.setVisibility(View.GONE);
			coverView.setVisibility(View.GONE);
			lockedIcon.setVisibility(View.GONE);
			timeText.setVisibility(View.GONE);
			// mRecordView.setVisibility(View.GONE);
			taskbarLayout.setVisibility(View.GONE);
			shareTimeLayout.setVisibility(View.GONE);
			shareButtonLayout.setVisibility(View.GONE);
			wmParams.width = (int) this.getResources().getDimension(
					R.dimen.share_window_width);
			wmParams.height = (int) this.getResources().getDimension(
					R.dimen.share_window_height);
			// wmParams.x = (int)
			// this.getResources().getDimension(R.dimen.share_window_x);
			// wmParams.y = (int)
			// this.getResources().getDimension(R.dimen.share_window_y);
			wmParams.gravity = Gravity.CENTER;
			wmParams.flags = LayoutParams.FLAG_ALT_FOCUSABLE_IM;
			// mSharePictureView.setVisibility(View.VISIBLE);
			showWarning(false);
			handlerShare.postDelayed(new Runnable() {

				@Override
				public void run() {
					Message msg = new Message();
					msg.what = 20160118;
					handlerShare.sendMessage(msg);
				}
			}, 5000);
			mWindowManager.updateViewLayout(view, wmParams);
			if (recorder != null) {
				// recorder.stopPreView();
				// recorder.startPreView();
				// recorder.setPreViewCallback(recorder);
			}
			isFullScreenShow = true;
			break;
		case SW_HIDE_SHARE_PICTURE:
			// if(recorder != null)
			// recorder.setPreViewCallback(null);
			view.setKeepScreenOn(false);
			wmParams.width = 1;
			wmParams.height = 1;
			wmParams.x = 0;
			wmParams.y = 0;
			wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
					| LayoutParams.FLAG_NOT_FOCUSABLE;
			if (recorder != null && recorder.isLocked()) {
				lockedIcon.setBackgroundColor(Color.BLACK);
				lockedIcon.setVisibility(View.GONE);
			} else {
				lockedIcon.setVisibility(View.GONE);
				coverView.setVisibility(View.VISIBLE);
			}
			timeText.setVisibility(View.VISIBLE);
			taskbarLayout.setVisibility(View.VISIBLE);
			shareTimeLayout.setVisibility(View.GONE);
			shareButtonLayout.setVisibility(View.GONE);
			mSharePictureView.setVisibility(View.GONE);
			showWarning(true);
			mWindowManager.updateViewLayout(view, wmParams);
			isFullScreenShow = false;
			state_window = 0;
			break;
		default:
			break;
		}
		nPreviewMode = flag;
	}

	Handler updateTime = new Handler();
	Runnable updateTimeThread = new Runnable() {
		@Override
		public void run() {
			long available = checkSDcard();
			if (available < 0)
				available = 0;

			timeText.setText(new SimpleDateFormat(
					getString(R.string.carrecorder_time_format), Locale.CHINA)
					.format(new Date()));
			updateTime.postDelayed(updateTimeThread, 1000);
		}
	};

	class ThreadShareTime implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (mIsSharing) {
				Message msg = new Message();
				msg.what = 3;
				handlerShare.sendMessage(msg);
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	Handler handlerShare = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				updateViewPosition(SW_HIDE_SHARE_VIDEO);
				sendShareBroadcast("com.cxb.sharevideo", mShareFile);
				closeActivity();
			} else if (msg.what == 2) {
				try {
					Thread.sleep(1000);
					updateViewPosition(SW_HIDE_SHARE_PICTURE);
					if (mIsSharing)
						sendShareBroadcast("com.cxb.sharepicture", mShareFile);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				closeActivity();
			} else if (msg.what == 3) {
				String shareTime = String.format("%dS", recorder.SHARE_TIME
						- recorder.getShareVideoDuration() / 1000);
				mShareTimeView.setText(shareTime);
			}
			// else if(msg.what == 20160116) {
			// // if(recorder != null && recorder.isBStart())
			// // recorder.startRecord();
			// }
			else if (msg.what == 20160118 || msg.what == 201601181) {
				if (mIsSharing)
					if (recorder != null) {
						if (201601181 == msg.what) {
							Log.d("pumkidc",
									"recorder.getShareVideoDuration() "
											+ recorder.getShareVideoDuration());
							if (recorder.getShareVideoDuration() == 0) {

								updateViewPosition(SW_HIDE_SHARE_VIDEO);
								closeActivity();
							}
						} else {
							if (currentFlag == SW_SHOW_SHARE_PICTURE) {

								updateViewPosition(SW_HIDE_SHARE_PICTURE);
								closeActivity();
							}
						}

					}
			}

			super.handleMessage(msg);
		};
	};

	private boolean deleteFile() {
		boolean bRet = false;
		File[] videoFile = new File(recorder.VIDEOS_PATH_NORMAL).listFiles();

		if (null != videoFile && videoFile.length > 0) {

			if (videoFile.length == 1) {
				// 只有一个文件
				return false;
			}

			File file = null;
			for (int i = 0; i < videoFile.length; i++) {
				if (videoFile[i].isFile()) {
					if (file == null)
						file = videoFile[i];
					else if (file.lastModified() > videoFile[i].lastModified())
						file = videoFile[i];
				}
			}

			if (file != null) {
				bRet = file.delete();
				file = null;
			}
			videoFile = null;
		}

		// ////////////////閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓锟�/////////////////////
		// 1.閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷疯皭閿熸枻鎷烽敓閾扮》鎷烽敓鏂ゆ嫹鍕熼敓锟�
		File[] oldVideoFiles = new File(VideoRecorder.SD_ROOT + "/CarRecord")
				.listFiles();
		if (oldVideoFiles != null) {
			for (File oldFile : oldVideoFiles) {
				if (oldFile.isFile()) {
					oldFile.delete();
				}
			}
		}

		if (mBinder != null)
			mBinder.onDeleteFileCallBack();

		return bRet;
	}

	public void checkExternalSDcardSize() {
		// File rootPath = new File(VideoRecorder.SD_ROOT);
		// long SDsize = rootPath.getTotalSpace() / 1024 / 1024;
		// if (SDsize < 2000) {
		// } else if (SDsize > 2000 && SDsize < 4000) {
		// } else if (SDsize > 4000) {
		// nAvailableMin = 300;
		// }

		nAvailableMin = 200 + persistUtils.getRecordTime() * 80;
	}

	public long checkSDcard() {
		File rootPath = new File(recorder.SD_ROOT);
		if (!isSDExists(this)) {
			showWarning(true, getString(R.string.cardverify));
			return -1;
		}

		checkExternalSDcardSize();

		long available = rootPath.getFreeSpace() / 1024 / 1024;
		Log.i("test", "recorder available=" + available);
		while ((available = rootPath.getFreeSpace() / 1024 / 1024) < nAvailableMin
				&& deleteFile()) {
			available = rootPath.getFreeSpace() / 1024 / 1024;
			Log.i("test", "recorder available=" + available);
		}

		if (available < nAvailableMin) {
			showWarning(true, getString(R.string.lowstorage));

		} else {
			showWarning(false, null);
		}
		return available;
	}

	public static boolean isSDExists(Context context) {

		long availableMemorySize = 0;

		long sdcard1 = getAvailableMemorySize(VideoRecorder.SD_ROOT);
		long sdcard2 = getAvailableMemorySize(VideoRecorder.SD_ROOT);

		return sdcard1 > 0 && sdcard2 > 0;

	}

	private void showWarning(boolean isShow, String strWarning) {
		if (isShow) {
			worningText.setText(strWarning);
			worningText.setVisibility(View.VISIBLE);
		} else {
			worningText.setVisibility(View.GONE);
		}
	}

	private void showWarning(boolean isShow) {

		if (isShow) {
			worning.setVisibility(View.VISIBLE);
		} else {
			worning.setVisibility(View.GONE);
		}
	}

	public static boolean isExternalStorageAvailable() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	public static long getAvailableMemorySize(String sdcardPath) {
		// String sdcard2 = "/mnt/sdcard2/";
		try {

			if (isExternalStorageAvailable()) {
				// File path =
				// Environment.getExternalStorageDirectory();//閿熸枻鎷峰彇SDCard閿熸枻鎷风洰褰�
				StatFs stat = new StatFs(sdcardPath);
				long blockSize = stat.getBlockSize();
				long availableBlocks = stat.getBlockCount();
				// long availableBlocks = stat.getAvailableBlocks();
				return availableBlocks * blockSize;
			} else {
				return -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.i("test", "surfaceChanged");
		this.surfaceHolder = holder;
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.i("test", "surfaceCreated");
		CarRecorderDebug.printfRECORDERLog("surfaceCreated");
		if (recorder == null) {
			recorder = VideoRecorder.getInstance(holder, this);
			recorder.clearShareImageCache();

		}
		recorder.setRecorderListener(new RecorderListener() {
			@Override
			public void onStarted() {
				// recordIcon.setVisibility(View.VISIBLE);
				setRecording(true);
				CarRecorderDebug
						.printfRECORDERLog("setRecorderListener onStarted");
				recordButton.setImageResource(R.drawable.stop_button);
			}

			@Override
			public void onStoped(boolean bStart) {
				// recordIcon.setVisibility(View.GONE);
				setRecording(false);
				CarRecorderDebug
						.printfRECORDERLog("setRecorderListener onStoped");
				recordButton.setImageResource(R.drawable.start_button);
				if (bStart)
					if (isSDExists(PreviewService.this)) {
						recorder.start(true);
					}
			}

			@Override
			public void onMute(boolean bMute) {
				// if (bMute)
				// muteIcon.setImageResource(R.drawable.mute);//
				// 閿熸埅鎲嬫嫹閿熸枻鎷烽敓鏂ゆ嫹褰曢敓鏂ゆ嫹
				// else
				// muteIcon.setImageResource(R.drawable.sound);//
				// 閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷峰綍閿熸枻鎷�
			}

			@Override
			public void onLocked(boolean bLocked) {
				updateViewPosition(nPreviewMode);
			}
		});

		if (firstBoot) {
			checkExternalSDcardSize();
			if (checkSDcard() >= nAvailableMin) {
				recorder.start(true);
			}
			firstBoot = false;
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		Log.i("test", "===surfaceDestroyed");
		if (recorder != null) {
			recorder.release();
			recorder = null;
		}
		surfaceView = null;
	}

	@Override
	public void onLowMemory() {
		CarRecorderDebug.printf("onLowMemory", szPath);
		Log.i("carRecorder", "===onLowMemory");
		if (recorder != null) {
			recorder.release();
			recorder = null;
		}
		surfaceView = null;
		super.onLowMemory();
	}

	@Override
	public void onDestroy() {
		CarRecorderDebug.printf("PreviewWindowService.OnDestroy", szPath);
		CarRecorderDebug
				.printfRECORDERLog("PreviewWindowService OnDestroy szPath "
						+ szPath);
		if (recorder != null) {
			recorder.releaseCamera();
		}
		updateTime.removeCallbacks(updateTimeThread);
		unregisterReceiver(mReceiverRecord);
		unregisterReceiver(mReceiverSD);
		unregisterReceiver(mReceiverShutDown);
		unregisterReceiver(mStartTestMode);

		mWindowManager.removeView(view);
		stopForeground(true);
		super.onDestroy();
	}

	public void showCarRecorderStart() {
		System.currentTimeMillis();
		Notification localNotification = new Notification();
		localNotification.flags = (0x2 | localNotification.flags);
		Context localContext = getApplicationContext();
		Intent localIntent = new Intent();
		localNotification.setLatestEventInfo(localContext, "", "",
				PendingIntent.getActivity(getApplicationContext(), 0,
						localIntent, 0));
		startForeground(1, localNotification);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MSG_HIDE_MENU_BAR:
			taskbarLayout.setVisibility(View.GONE);
			menuBarHideTimeCount = 0;
			break;

		default:
			break;
		}
		return false;
	}

	private void playTts(String text) {

		Utils.playTts(this, text, true);
	}

	private void shutDown() {

		RootContext.getInstance(this).runCommand("reboot -p");
	}

	@Override
	public void onImageComplete() {
		if (isPowerOffing) {
			CarRecorderDebug.printfPhotoLog("onImageComplete");
			shutDown();
		}

	}

	class DimissDialogTask implements Runnable {
		@Override
		public void run() {
			if (lockedFile2More != null && lockedFile2More.isShowing()) {
				lockedFile2More.dismiss();
			}

		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}

	class DeleteFileService extends Binder {
		private IDeleteFile mDeleteFileCallBack = null;

		public void setDeleteFileCallBack(IDeleteFile callBack) {
			mDeleteFileCallBack = callBack;
		}

		public void onDeleteFileCallBack() {
			if (mDeleteFileCallBack != null)
				mDeleteFileCallBack.onDeleteFile();
		}
	}

}

interface OnImageUploadCallBack {
	void onImageComplete();

}

interface IDeleteFile {
	void onDeleteFile();
}
